package com.atguigu.gulimall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.authserver.feign.MemberFeignService;
import com.atguigu.gulimall.authserver.feign.ThirdPartFeignService;
import com.atguigu.gulimall.authserver.vo.MemberUserLoginVo;
import com.atguigu.gulimall.authserver.vo.UserLoginVo;
import com.atguigu.gulimall.authserver.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.atguigu.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @author jingchun
 * @create 2024-07-15 23:12
 */

@Controller
public class LoginController {
	@Autowired
	ThirdPartFeignService thirdPartFeignService;

	@Autowired
	StringRedisTemplate redisTemplate;

	@Autowired
	MemberFeignService memberFeignService;

	@ResponseBody
	@GetMapping("/sms/sendCode")
	public R sendCode(@RequestParam("phone") String phone) {
		//1.接口防刷
		String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
		String redisCode = redisTemplate.opsForValue().get(key);
		if (!StringUtils.isEmpty(redisCode)) {
			long l = Long.parseLong(redisCode.split("_")[1]);
			if (System.currentTimeMillis() - l < 60000) {
				//60s内不能再发
				return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
			}
		}

		//2.验证码存到Redis
		//String code = UUID.randomUUID().toString().substring(0,5);
		int number = (int) ((Math.random() * 9 + 1) * 100000);
		String code = String.valueOf(number);
		String substring = code + "_" + System.currentTimeMillis();
		System.out.println("substring的内容" + substring + "code的内容是" + code);
		redisTemplate.opsForValue().set(key, substring, 10, TimeUnit.MINUTES);

		R r = thirdPartFeignService.sendCode(phone, code);
		System.out.println("LoginController" + r.getCode() + r.getData("msg", new TypeReference<String>() {
		}));

		return R.ok();
	}

	@PostMapping("/register")
	public String register(@Valid UserRegisterVo vos, BindingResult result, RedirectAttributes attributes) {
		//如果有错误，就返回到注册页面
		if (result.hasErrors()) {
			Map<String, String> errors =
					result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
							FieldError::getDefaultMessage));
			attributes.addFlashAttribute("errors", errors);
			//效验出错回到注册页面
			return "redirect:http://auth.gulimall.com/reg.html";
		}

		//1.校验验证码
		String code = vos.getCode();

		//	获取存入Redis里的验证码
		String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
		if (!StringUtils.isEmpty(redisCode)) {
			//截取字符串
			if (code.equals(redisCode.split("_")[0])) {
				//删除验证码
				redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
				//验证码通过，真正注册，调用远程服务
				R register = memberFeignService.register(vos);
				if (register.getCode() == 0) {
					//成功
					return "redirect:http://auth.gulimall.com/login.html";
				} else {
					//失败
					Map<String, String> errors = new HashMap<>();
					errors.put("msg", register.getData("msg", new TypeReference<String>() {
					}));
					attributes.addFlashAttribute("errors", errors);
					return "redirect:http://auth.gulimall.com/reg.html";
				}
			} else {
				//		校验失败返回注册页面
				Map<String, String> errors = new HashMap<>();
				errors.put("code", "验证码错误");
				attributes.addFlashAttribute("errors", errors);
				return "redirect:http://auth.gulimall.com/reg.html";

			}
		} else {
			Map<String, String> errors = new HashMap<>();
			errors.put("code", "验证码错误");
			attributes.addFlashAttribute("errors", errors);
			return "redirect:http://auth.gulimall.com/reg.html";
		}
	}

	@PostMapping("/login")
	public String login(UserLoginVo vos, RedirectAttributes attributes, HttpSession session) {


		//远程登录
		R login = memberFeignService.login(vos);
		if (login.getCode() == 0) {
			MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {
			});
			session.setAttribute(LOGIN_USER,data);
			return "redirect:http://gulimall.com";
		} else {
			//失败
			Map<String, String> errors = new HashMap<>();
			errors.put("msg", login.getData("msg", new TypeReference<String>() {
			}));
			attributes.addFlashAttribute("errors", errors);
			return "redirect:http://auth.gulimall.com/login.html";
		}

	}

	@GetMapping(value = "/login.html")
	public String loginPage(HttpSession session) {

		//从session先取出来用户的信息，判断用户是否已经登录过了
		Object attribute = session.getAttribute(LOGIN_USER);
		//如果用户没登录那就跳转到登录页面
		if (attribute == null) {
			return "login";
		} else {
			return "redirect:http://gulimall.com";
		}

	}

}


